<!-- 待出餐/待送达/待退款 -->
<template>
  <view class="content">
    <up-tabs :list="list" @change="tabChange" :current="currentTab" :activeStyle="{ color: '#3c9cff' }"></up-tabs>
    <view class="main">
      <view class="item" v-for="item in showAll ? allOrder : kindOrder" :key="item._id">
        <view class="seller">
          <view class="s_left">
            <view class="s_name">{{ item.order[0].sellerName }}</view>
            <view class="s_arr"></view>
          </view>
          <view class="s_right">
            <view class="s_evaluate">
              {{ item.status }}
            </view>
            <view class="s_delete"></view>
          </view>
        </view>
        <view class="goods">
          <img :src="item.order[0].goods[0].icon" alt="">
          <view class="g_right">
            <view class="r_top">
              <view class="g_name">{{ item.order[0].goods[0].name }}</view>
              <view class="g_price">￥{{ item.order[0].goods[0].price }}</view>
            </view>
            <view class="r_bottom">
              <view class="g_detail">{{ item.order[0].goods[0].dec }}</view>
              <view class="g_num">x{{ item.order[0].goods[0].count }}</view>
            </view>
          </view>
        </view>
        <view class="bottom">
          <view class="b_left">
            <view class="g_total">共 {{ item.totalCount }} 件商品金额</view>
            <view class="g_price">￥{{ item.totalMoney }}</view>
          </view>
          <view class="b_right">
            <view class="b_evaluate" @click="handlerEvent(item._id)">
              {{ item.status }}
            </view>
          </view>
        </view>
      </view>

    </view>
  </view>

</template>

<script setup>
import { ref, reactive, onMounted, onActivated } from 'vue';
import { searchAllOrder, searchSellerAllOrder } from "@/api/order";
import useUserStore from '@/store/modules/user'
import useOrderStore from "@/store/modules/order";
let orderStore = useOrderStore();
const userStore = useUserStore()

// 创建响应式数据  
let list = reactive([
  { name: '全部', badge: { value: 0 } },
  { name: '待出餐', badge: { value: 0 } },
  { name: '待送达', badge: { value: 0 } },
  // { name: '带取餐', badge: { isDot: true } },
  { name: '待退款', badge: { value: 0 } },
]);

/**
 * tab栏切换事件处理
 */
// 是否为全部显示
let showAll = ref(true)
// 专门放置某一类的餐品
let kindOrder = ref([])
function tabChange(val) {
  kindOrder.value = []
  console.log(val);
  if (val.index !== 0) {
    showAll.value = false
  } else {
    showAll.value = true
  }
  if (val.index == 1) {
    kindOrder.value = kindOrder.value.concat(allOrder.value.filter(item => item.status === '待出餐'));
  } else if (val.index == 2) {
    kindOrder.value = kindOrder.value.concat(allOrder.value.filter(item => item.status == '待送达'));
  } else if (val.index == 3) {
    kindOrder.value = kindOrder.value.concat(allOrder.value.filter(item => item.status == '待退款'));
  }
}

/**
 * 查询用户所有订单
 */
let allOrder = ref([])
let getInfo = () => {
  searchSellerAllOrder({ sellerId: userStore.userId }).then(res => {
    if (res.code == 200) {
      allOrder.value = res.data
      if (res.data.length > 0) {
        AddStatus(allOrder.value)
        tabChange({ index: currentTab.value })
        getBadge()
        let endTime = Number(allOrder.value[0].startTime) + 10 * 60 * 1000;
        if (endTime - Date.now() >= 0) {
          getRemainTime(allOrder.value[0])
        }
        console.log(allOrder.value);
      }

    }
  })
}
getInfo()

// 为所有订单加上状态字段
let AddStatus = (data) => {
  allOrder.value = data.map(order => {
    return { ...order, status: orderStatus(order.startTime, order.isPay, order.isSend, order.isReceive) }
  });
  console.log('allOrder: ', allOrder.value);
}
/**
 * 角标的计算
 */
function getBadge() {
  console.log('allOrder:jjjjj ', allOrder.value);
  // list[0].badge.value = allOrder.value.length;
  list[1].badge.value = allOrder.value.filter(item => item.status === '待出餐').length;
  list[2].badge.value = allOrder.value.filter(item => item.status === '待送达').length;
  list[3].badge.value = allOrder.value.filter(item => item.status === '待退款').length;
}
// 监听页面激活
onActivated(() => {
  getInfo()
});
/**
 * 判断当前订单的状态
 */
const orderStatus = (time, isPay, isSend, isReceive) => {
  const currentTime = new Date();
  const orderTime = new Date(Number(time));
  const timeDiff = (currentTime - orderTime) / (1000 * 60); // 计算时间差，单位为分钟

  if (timeDiff > 10 && !isPay) {
    return '超时';
  }

  if (!isPay) {
    return '待付款';
  }

  if (!isSend) {
    return '待出餐';
  }

  if (!isReceive) {
    return '待送达';
  }

  return '已完成';
};

const props = defineProps({
  currentTabIndex: {
    type: String || Number,
    default: ''
  },
});
// console.log('currentTabIndex: ', props.currentTabIndex);
// 控制当前激活的标签页
const currentTab = ref(props.currentTabIndex ? Number(props.currentTabIndex) : 0);
console.log('currentTab: ', currentTab);
/**
 * 跳转到订单页面
 */
const handlerEvent = (id) => {
  orderStore.addCurrentOrderId(id);
  getInfo()
  uni.navigateTo({ url: "/pages/components/order/settlement" });
}
/**
 * 当第一个订单的时间结束时, 刷新订单
 */
/**
 * 订单剩余支付时间计算
 */
let timer = null; // 定时器
function getRemainTime(order) {
  // 清除之前的定时器
  clearTimer();

  // 获取下单时间戳
  const startTime = Number(order.startTime);
  const endTime = startTime + 10 * 60 * 1000;

  // 更新剩余时间
  function updateRemainTime() {

    const now = Date.now(); // 当前时间
    const remainingTime = endTime - now;

    if (remainingTime > 0) {
      return
    } else {
      clearTimer(); // 停止定时器
      getInfo()
    }
  }

  // 启动定时器，每秒更新一次剩余时间
  timer = setInterval(updateRemainTime, 1000);
  updateRemainTime(); // 立即更新一次
}

// 清除定时器的方法
function clearTimer() {
  if (timer) {
    clearInterval(timer);
    timer = null; // 重置 timer 变量
  }
}
</script>

<style lang="scss" scoped>
.content {
  // height: calc(100vh);
  /* #ifdef H5 */
  // height: calc(100vh - var(--window-top) - 100rpx);
  height: calc(100vh - var(--window-top));
  /* #endif */
  display: flex;
  flex-direction: column;
  position: relative;
  background-color: $uni-bg-color-grey;
  overflow: auto;


  .main {
    overflow: auto;

    .item {
      width: 100%;
      display: flex;
      flex-direction: column;
      background-color: white;
      color: $uni-text-color;
      margin-bottom: 26rpx;
      box-shadow: 0 0 10px 5px rgba(240, 240, 240, 0.2);

      .seller {
        width: 100%;
        display: flex;
        justify-content: space-between;
        padding: 10rpx 30rpx;
        border-bottom: 2rpx solid #f0f0f0;

        .s_left {
          font-style: 28rpx;
          font-weight: 600;
          display: flex;
          align-items: center;

          .s_arr {
            width: 32rpx;
            height: 32rpx;
            background-image: url("@/assets/orderRecord/arr_right.svg");
            background-size: cover;
          }
        }

        .s_right {
          font-size: 24rpx;
          font-weight: 600;
          display: flex;
          align-items: center;

          .s_delete {
            width: 32rpx;
            height: 32rpx;
            background-image: url("@/assets/orderRecord/delete.svg");
            background-size: cover;
            margin-left: 4rpx;
          }
        }
      }

      .goods {
        width: 100%;
        display: flex;
        align-items: center;
        padding: 30rpx;

        img {
          width: 150rpx;
          height: 150rpx;
          border-radius: 16rpx;
        }

        .g_right {
          display: flex;
          flex: 1;
          padding: 0 20rpx;
          flex-direction: column;
          justify-content: space-around;

          .r_top {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .g_name {
              font-size: 28rpx;
              font-weight: 600;
            }

            .g_price {
              font-size: 24rpx;
              font-weight: 600;
            }
          }

          .r_bottom {
            display: flex;
            width: 100%;
            align-items: center;
            font-size: 20rpx;
            color: $uni-text-color-grey;
            margin-top: 20rpx;
            justify-content: space-between;
          }
        }

      }

      .bottom {
        width: 100%;
        display: flex;
        padding: 20rpx 30rpx;
        font-size: 24rpx;
        color: $uni-text-color-grey;
        justify-content: space-between;
        border-top: 2rpx solid #f0f0f0;

        .b_left {
          display: flex;
          align-items: center;

          .g_price {
            color: $uni-text-color;
            font-weight: 600;
            margin-left: 5rpx;
          }
        }

        .b_right {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 140rpx;
          height: 60rpx;
          font-size: 28rpx;
          color: white;
          background-color: $uni-text-color-grey2;
          border-radius: 12rpx;
        }
      }
    }
  }

}

:deep(.u-tabs__wrapper__nav__item) {
  flex: 1;
}
</style>